package com.bpmn.flow.cmd;

import cn.hutool.core.collection.CollUtil;
import com.bpmn.common.holder.TenantContextHolder;
import com.bpmn.flow.handler.TaskTimeoutJobHandler;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.job.service.TimerJobService;
import org.flowable.job.service.impl.persistence.entity.JobEntity;
import org.flowable.job.service.impl.persistence.entity.TimerJobEntity;

import java.util.Date;
import java.util.List;

/**
 * 任务超时处理
 *
 * @author rain
 */
public class TimeoutCmd implements Command<Boolean> {

    protected String processInstanceId;

    protected String taskId;

    protected Date dueDate;

    public TimeoutCmd(String processInstanceId, String taskId, Date dueDate) {
        this.processInstanceId = processInstanceId;
        this.taskId = taskId;
        this.dueDate = dueDate;
    }

    @Override
    public Boolean execute(CommandContext commandContext) {
        TimerJobService timerJobService = CommandContextUtil.getTimerJobService();
        //删除之前已经存在的定时任务
        List<TimerJobEntity> timerJobEntityList = timerJobService.findTimerJobsByProcessInstanceId(processInstanceId);
        if (CollUtil.isNotEmpty(timerJobEntityList)) {
            for (TimerJobEntity timerJobEntity : timerJobEntityList) {
                String configuration = timerJobEntity.getJobHandlerConfiguration();
                if (taskId.equals(configuration)) {
                    timerJobService.deleteTimerJob(timerJobEntity);
                }
            }
        }
        //创建job对象
        TimerJobEntity timer = timerJobService.createTimerJob();
        timer.setTenantId(TenantContextHolder.getTenantId());
        //设置job类型
        timer.setJobType(JobEntity.JOB_TYPE_TIMER);
        timer.setJobHandlerType(TaskTimeoutJobHandler.TYPE);
        timer.setDuedate(dueDate);
        timer.setProcessInstanceId(processInstanceId);
        //设置任务id
        timer.setJobHandlerConfiguration(taskId);
        //保存并触发事件
        timerJobService.scheduleTimerJob(timer);
        return true;
    }
}
